<template>
  <el-form ref="ruleFormRef" style="max-width: 600px; margin: 0 auto" :model="ruleForm" :rules="rules" label-width="auto"
    class="demo-ruleForm" :size="formSize" status-icon>
    <div class="search-container" editorConfig.scroll="false">
      <el-form-item label="供应商类型" prop="supplier_VendorType">
        <el-radio-group v-model="ruleForm.vendorType" class="ml-4">
           <el-radio value="个人">个人</el-radio>
        <el-radio value="企业">企业</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-form-item label="负责人手机号" prop="supplier_ResponsiblePhone">
            <el-input v-model="ruleForm.responsiblePhone" placeholder="请输入负责人手机号" />
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item label="负责人姓名" prop="supplier_ResponsibleName">
            <el-input v-model="ruleForm.responsibleName" placeholder="请输入负责人姓名" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-form-item label="供应商姓名" prop="supplier_VendorName">
            <el-input v-model="ruleForm.vendorName" placeholder="请输入供应商姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item label="身份证" prop="supplier_IdentityCard">
            <el-input v-model="ruleForm.identityCard" placeholder="请填写身份证" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="所在地" prop="supplier_IdentityCard">
        <el-input v-model="ruleForm.arearAdd" id="searchInputId" class="common-layout" size="small" placeholder="输入关键词搜索位置"
            style="height:25px;width:26%;margin-left:1%;" />
        <el-button @click="searchLocation">搜索</el-button>
        <div class="gdmap-container">
            <div id="container" style="width: 100%; height: 300px;"></div>
        </div>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-form-item label="所属行业" prop="supplier_IndustryName">
            <el-input v-model="ruleForm.industryName" />
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item label="统一社会信用代码" prop="supplier_UnifiedSocialCreditCode">
            <el-input v-model="ruleForm.unifiedSocialCreditCode" placeholder="请填写统一社会信用代码(税号)" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-form-item label="助记码" prop="supplier_Mnemonics">
            <el-input v-model="ruleForm.mnemonics" />
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item label="供应商属性" prop="supplier_VendorAttributes">
            <el-input v-model="ruleForm.vendorAttributes" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-form-item label="所属单位" prop="supplier_BusinessId">
             <el-select v-model="ruleForm.businessId" placeholder="所属单位">
        <el-option label="总部" :value="1" />
        <el-option label="分公司" :value="2"/>
      </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item label="引用单位" prop="supplier_UnitsOfReference">
            <el-input v-model="ruleForm.unitsOfReference" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="使用状态" prop="supplier_UseState">
        <el-radio-group v-model="ruleForm.useState" class="ml-4">
          <el-radio :value="true">启用</el-radio>
        <el-radio :value="false">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="supplier_VendorDesc">
        <div style="border: 1px solid #ccc">
          <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" />
          <Editor style="height: 500px; overflow-y: hidden" v-model="ruleForm.vendorDesc"
            @on-created="handleCreated" />
        </div>
      </el-form-item>
    </div>
    <div class="search-container">
      <el-form-item>
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="所属市场" prop="supplier_Markets">
              <el-select v-model="ruleForm.markets" style="width: 120px" placeholder="--请选择所属市场--" clearable>
                 <el-option label="玉林市犀浦镇牛羊市场" value="玉林市犀浦镇牛羊市场" />
        <el-option label="贺州市龙州县牛羊市场" value="贺州市龙州县牛羊市场" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="业务员" prop="supplier_Salesman">
              <el-select v-model="ruleForm.salesman" style="width: 120px" placeholder="--请选择业务员--" clearable>
                 <el-option label="刘永刚" value="刘永刚" />
        <el-option label="孟盘龙" value="孟盘龙" />
        <el-option label="赵秋实" value="赵秋实" />
        <el-option label="牛骞若" value="牛骞若" />
        <el-option label="赵思彤" value="赵思彤" />
        <el-option label="于晋哲" value="于晋哲" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        修改
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
    </div>
  </el-form>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import purcure from '@/api/PurchaseMent/index'
import { purcoreQuery,buildingIdQuery } from '@/api/PurchaseMent/model'
import vendor from '@/api/VendorMangMent/index'
import { vendorQuery } from '@/api/VendorMangMent/model'
import { useRouter, useRoute } from 'vue-router'
import AMapLoader from "@amap/amap-jsapi-loader";
const route = useRoute()
//富文本
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
const ruleForm = reactive({
  "vendorSnowId": 0,
  "venDorCode": "",
  "vendorType": "",
  "responsiblePhone": "",
  "responsibleName": "",
  "vendorName": "",
  "identityCard": "",
  "arearAdd": "",
  "industryName": "",
  "unifiedSocialCreditCode": "",
  "mnemonics": "",
  "vendorAttributes": "",
  "businessId": null,
  "useState": true,
  "unitsOfReference": "",
  "vendorDesc": "",
  "markets": "",
  "salesman": "",
  "createBy": 0,
  "createTime": "2024-04-07",
  "updateBy": 0,
  "updateTime": "2024-04-07",
  "isDel": true
})
//反填
//查看
const view = () => {
    vendor.editvendor(route.query.vendorSnowId).then(res=>{
        ruleForm.arearAdd = res.data.arearAdd
        ruleForm.businessId = res.data.businessId
        ruleForm.createBy = res.data.createBy
        ruleForm.createTime = res.data.createTime
        ruleForm.identityCard = res.data.identityCard
        ruleForm.industryName = res.data.industryName
        ruleForm.isDel = res.data.isDel
        ruleForm.mnemonics = res.data.mnemonics
        ruleForm.markets = res.data.markets
       ruleForm.responsibleName = res.data.responsibleName
       ruleForm.salesman = res.data.salesman
       ruleForm.updateBy = res.data.updateBy
       ruleForm.updateTime = res.data.updateTime
       ruleForm.vendorDesc = res.data.vendorDesc
       ruleForm.vendorName = res.data.vendorName
       ruleForm.vendorType = res.data.vendorType
       ruleForm.venDorCode = res.data.venDorCode
      ruleForm.responsiblePhone = res.data.responsiblePhone
       ruleForm.unitsOfReference= res.data.unitsOfReference
      ruleForm.useState = res.data.useState
      ruleForm.vendorAttributes = res.data.vendorAttributes
      ruleForm.unifiedSocialCreditCode = res.data.unifiedSocialCreditCode
      ruleForm.vendorSnowId = res.data.vendorSnowId
       console.log(form)
    })
}
onMounted(()=>{
    view()
})
//表单
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
//刷新数据
const emit = defineEmits(["addOK"]);
const rules = reactive<FormRules<RuleForm>>({
  name: [
    { required: true, message: 'Please input Activity name', trigger: 'blur' },
    { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
})
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      vendor.edit(ruleForm).then(res => {
        if (res.code > 0)
        {
          ElMessage.success("修改成功");
          emit("addOK");
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
//地图
let map: any = null; // Define map variable with proper type
let placeSearch: any = null; // Define placeSearch variable

function initMap() {
    window._AMapSecurityConfig = {
        securityJsCode: "0e64b586350a7d7cc08c9d0be36e8923", // 密钥
    };	// Important!
    AMapLoader.load({
        key: "3901bbb7e4598de04e06cabcf21f2b47", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
            'AMap.AutoComplete',
            'AMap.PlaceSearch'
        ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    })
        .then((AMap) => {
            map = new AMap.Map("container", {
                resizeEnable: true,
                viewMode: "3D", // 是否为3D地图模式
                zoom: 8, // 初始化地图级别
                center: [118, 30], // 初始化地图中心点位置
            });
            const autoOptions = {
                input: "searchInputId"
            };
            const auto = new AMap.AutoComplete(autoOptions);
            placeSearch = new AMap.PlaceSearch({
                map: map
            });
            auto.on("select", handleSelect);
        });
}

function handleSelect(e: any) {
    placeSearch.setCity(e.poi.adcode);
    placeSearch.search(e.poi.name, (status: string, result: any) => {
        if (status === 'complete' && result.info === 'OK') {
            // Assuming first result contains detailed address info
            const selectedLocation = result.poiList.pois[0];
            const addressInfo = `${selectedLocation.name}, ${selectedLocation.address}`;
            console.log("Selected location:", addressInfo);
            // Set state to display detailed address info
          selectedLocationInfo.value = addressInfo;
            ruleForm.arearAdd=selectedLocation.name

        }
    });
}

onMounted(() => {
    console.log("onmounted");
    initMap();
});

onUnmounted(() => {
    if (map) {
        map.destroy();
    }
});

const selectedLocationInfo = ref(''); // Reactive variable to hold detailed address info

const searchLocation = () => {

    console.log(ruleForm.arearAdd);
};
</script>
<style scoped>
.gdmap-container{
    width: 500px;
    height:300px;
}
#container {
  padding: 0px;
  margin: 0px;
  border:1px solid gray;
  width: 100%;
  height: 100%;
}
</style>